package com.sam.im.heiqun.uis.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.utils.JudgeIDCard;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.sam.im.heiqun.view.EditTextWithDel;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseActivity;

import java.text.ParseException;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 实名认证
 * createby lei 20170523
 */
public class AutoCheckActvity extends BaseActivity implements Handler.Callback {
    public static final int REQUEST_COUNTRY = 1000;
    private static final int HEAD_IMG_URL = 1001;
    public static final int TIME_SUB = 1002;
    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.pre_tv_title)
    TextView preTvTitle;
    @BindView(R.id.edittext)
    EditTextWithDel edittext;
    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.ok)
    TextView ok;
    @BindView(R.id.country)
    TextView country;
    @BindView(R.id.country_code)
    TextView countryCode;
    @BindView(R.id.phone_number)
    EditText phoneNumber;
    @BindView(R.id.get_sign)
    TextView getSign;
    @BindView(R.id.auth_code)
    EditText authCode;
    @BindView(R.id.username_ed)
    EditText usernameEd;
    @BindView(R.id.idcard)
    EditText idcard;
    @BindView(R.id.docheck)
    Button docheck;
    private int timeNum = 60;
    private Handler handler = new Handler(this);
    PGService mPgService;
    private String mobileStr = "+86";
    private String countryStr;
    @Override
    public int getContentViewId() {
        return R.layout.activity_auto_check_actvity;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        mPgService = PGService.getInstance();
        preTvTitle.setText(getResources().getString(R.string.real_name_approve));
    }

   /* @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }*/

    @OnClick({R.id.country_code, R.id.get_sign, R.id.docheck,R.id.country,R.id.pre_v_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                finish();
                break;
            case R.id.country:
            case R.id.country_code:
                startActivityForResult(CountrySelectActivity.class, REQUEST_COUNTRY);
                break;
            case R.id.get_sign:
                String phoneNumberStr = phoneNumber.getText().toString().trim();
                boolean isMobileNO = ToolsUtils.isMobile(phoneNumberStr);

                if (phoneNumberStr.length() > 0) {
                    if (!isMobileNO){
                        Log.i("info","phone=="+phoneNumberStr);
                        showToast(getResources().getString(R.string.error_phone));
                        return;
                    }
                    getSign.setEnabled(false);
                    getSign.setText(timeNum + "s");
                    getSign.setTextColor(getResources().getColor(R.color.middle_gray_2));
                    handler.sendEmptyMessageDelayed(TIME_SUB, 1000);
                    getValidateNum(mobileStr + phoneNumberStr);
                }
                break;
            case R.id.docheck:
                if (isReady()){//开始验证
                    updateAuth();
                }
                break;
        }
    }
    /**
     * 获取验证码
     */
    private void getValidateNum(String phoneNumber) {

        mPgService.getValidateNum(phoneNumber).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            public void onNext(ValidateEntivity s) {
                // 这里没做验证码的成员变量存储。也就是不做本地验证码判断
                //authCode.setText(s.getInfo().toString());
                // 查询注册账号是否有推荐人
                // queryReferee();
            }

            @Override
            protected void onResultError(ApiException ex) {
                if (ex.getCode()==-1){
//                    showToast(getResources().getString(R.string.phone_error));
                    try {

                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(ex.getDisplayMessage());
                        com.alibaba.fastjson.JSONObject data = object.getJSONObject("data");

                        showToast(data.getString("info"));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else {
                    showToast(getResources().getString(R.string.net_visit_exception));
                }
            }
        });
    }
    @Override
    public boolean handleMessage(Message message) {
        switch (message.what){
            case TIME_SUB:
                timeNum--;
                if (timeNum > 0) {
                    getSign.setText(timeNum + "s");
                    handler.sendEmptyMessageDelayed(TIME_SUB, 1000);
                } else {
                    getSign.setText(R.string.get_auth_code);
                    getSign.setTextColor(getResources().getColor(R.color.colorAccent));
                    timeNum = 60;
                    getSign.setEnabled(true);
                }
                break;
        }
        return false;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_COUNTRY:
                    countryStr = data.getStringExtra("country");
                    mobileStr = data.getStringExtra("mobileCode");
                    country.setText(countryStr);
                    countryCode.setText(mobileStr);
                    break;
            }
        }
    }
    private boolean isReady(){
        Log.i("info","====="+phoneNumber.getText().toString());
        if ("".equals(phoneNumber.getText().toString())){
            showToast(getResources().getString(R.string.nonull_phone));
            //ToastUtil.showtoast(AutoCheckActvity.this,"手机号码不能为空");
            return false ;
        }
        if ("".equals(authCode.getText().toString())){
            showToast(getResources().getString(R.string.nonull_yzm));
            //ToastUtil.showtoast(AutoCheckActvity.this,"验证码不能为空");
            return  false ;
        }
        if ("".equals(usernameEd.getText().toString())){
            showToast(getResources().getString(R.string.nonull_name));
            // ToastUtil.showtoast(AutoCheckActvity.this,"姓名不能为空");
            return  false ;
        }
        if ("".equals(idcard.getText().toString())){
            showToast(getResources().getString(R.string.nonull_sfz));
            //  ToastUtil.showtoast(AutoCheckActvity.this,"身份证号码不能为空");
            return false  ;
        }

        if (authCode.length() > 8) {
            showToast(getResources().getString(R.string.yzm_out_8));
            return false;
        }
        if (usernameEd.length() > 15) {
            showToast("昵称长度不能大于15");
            return false;
        }
        if (idcard.length() > 20) {
            showToast("身份证号长度不能大于20");
            return false;
        }

        return true ;
    }
    /**
     * 实名认证
     */
    private void updateAuth() {
        if (!ToolsUtils.currentNetState(this)) {
            return;
        }
        showProgress(null);
        final String name = usernameEd.getText().toString().trim();
        final String idCardcode = idcard.getText().toString().trim();
        final String auth = authCode.getText().toString().trim();
        final String mobile = phoneNumber.getText().toString().trim();
        final String countrycode = countryCode.getText().toString().trim();
        try {
            String s = JudgeIDCard.IDCardValidate(idCardcode);
            if (!"".equals(s)) {
                hideProgress();
                showToast(s);
                return;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String userId = ToolsUtils.getMyUserId();
        mPgService.updateAuth(name, auth, userId, idCardcode, countrycode+ mobile).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
//                ex.getCode()
                switch (ex.getCode()){
                    case 0 ://审核中
                        showToast(getResources().getString(R.string.auth_look_ing));
                        break;
                    case 2 ://身份证已被占用
                        showToast(getResources().getString(R.string.auth_idcard_have));
                        break;
                }

                hideProgress();
            }

            @Override
            public void onNext(ValidateEntivity validateEntivity) {
                hideProgress();
                //showToast(getString(R.string.data_already_commit_please_wait_approve));
                showToast(validateEntivity.getInfo());
                UserEntivity user = ToolsUtils.getUser();
                user.setIsAuth(1);
                user.setIdNo(idCardcode);
                user.setRealName(name);
                user.save();
                finish();
            }
        });

    }
}
